#! /usr/bin/env python
"""
Synopsis: 
	Mobile Analysis Client: Emulates mobile (e.g. iPhone) browser enviroments to analyze malicious websites
	
Usage:
	python mobile.py [ options ] url
	
Options:
	-h	--help			Display help information
	-a	--useragent=<agent> 	Select a specific user agent	

Required Modules:
	PyParsing	<http://pyparsing.wikispaces.com/>
	BeautifulSoup	<http://www.crummy.com/software/BeautifulSoup/>
	v8		<http://code.google.com/p/v8/>
	pyv8		<http://code.google.com/p/pyv8/>
	boost::Python	<http://www.boost.org/>
"""

import getopt
import sys
import configuration
from parse import *

# Show the program usage to the user
def usage():
	print __doc__
	sys.exit(1)

def main(URL):
	print "\n[*] Initializing Mobile Analysis Client"
	print "=" * 75
	print "\t--> Landing Page: " + URL
	print "\t--> User Agent  : " + configuration.CURRENT_USER_AGENT['details']	
	print "=" * 75
	
	try:
		# Create a new parser for this URL
		page_parser = Parser(URL)
	
		# Check if the website appears to be doing server side checking, only if allowed by the configuration
		print "\n[*] Checking if site performs server side user agent checking."
		if configuration.CHECK_SERVER_SIDE and page_parser.checking_server_side():
			print "[*] This site appears to be checking user agents on the server side. Checking all available user agents.\n"
		
			for user_agent in configuration.useragents.USER_AGENTS:
				configuration.CURRENT_USER_AGENT = user_agent
				print "\t--> Changed User Agent: " + user_agent['details']
				page_parser.analyze()
			
		else:
			print "[*] This site appears to be serving similar scripts for differing user agents, or CHECK_SERVER_SIDE is set to False.\n"
			page_parser.analyze()
	except:
		print "[!] Failed to initialize the parser"

if __name__ == "__main__":
	try:
		# Attempt to read the arguments passed in by the user
		options, args = getopt.getopt(sys.argv[1:], "hu:", ["help", "useragent="])
		URL = ''.join(args)
	
	except getopt.GetoptError, err:
		# Error, show usage
		print str(err)
		usage()
		sys.exit(2)
		
	if not options and not args:
		usage()
		
	# Setup default browser enviroment
	configuration.CURRENT_USER_AGENT = configuration.useragents.USER_AGENTS[0]
		
	# Loop through all options and set the variables as necessary
	for option in options:
		if option[0] == "-h" or option[0] == "--help":
			usage()
			
		if option[0] == "-u" or option[0] == "--useragent":
			for useragent in configuration.useragents.USER_AGENTS:
				if str(useragent['id']) == option[1] or useragent['name'] == option[1]:
					configuration.CURRENT_USER_AGENT = useragent
	
	# Execute on given URL				
	main(URL)
	
	print "=" * 75
	print "\t--> Finished"
	print "=" * 75 + "\n"
